
package ui;

import security.auth.UserManager;
import session.Session;

import javax.swing.*;
import java.awt.*;

public class AdminCreateUserDialog extends JDialog {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JComboBox<String> levelCombo;

    public AdminCreateUserDialog(JFrame parent) {
        super(parent, "创建用户", true);
        setSize(350, 250);
        setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        panel.add(new JLabel("用户名:"));
        usernameField = new JTextField();
        panel.add(usernameField);

        panel.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        panel.add(passwordField);

        panel.add(new JLabel("权限级别:"));
        levelCombo = new JComboBox<>(new String[]{"普通用户", "管理员"});
        panel.add(levelCombo);

        JButton confirmButton = new JButton("创建");
        confirmButton.addActionListener(e -> createUser());
        panel.add(confirmButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dispose());
        panel.add(cancelButton);

        add(panel);
        setVisible(true);
    }

    private void createUser() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword()).trim();
        int level = levelCombo.getSelectedIndex() == 0 ?
            UserManager.NORMAL_LEVEL :
            UserManager.ADMIN_LEVEL;

        // 输入验证
        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                "用户名和密码不能为空",
                "创建错误",
                JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 调用UserManager创建用户
        if (UserManager.createUser(username, password, level)) {
            JOptionPane.showMessageDialog(this,
                "用户 " + username + " 创建成功！\n权限级别: " +
                (level == UserManager.ADMIN_LEVEL ? "管理员" : "普通用户"),
                "创建成功",
                JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } else {
            JOptionPane.showMessageDialog(this,
                "创建失败: 用户名可能已存在",
                "创建错误",
                JOptionPane.ERROR_MESSAGE);
        }
    }
}
